import random
from django.db import transaction
from rest_framework import permissions
from rest_framework.decorators import action
from rest_framework.views import APIView
from utils import response_error, response_ok
from utils.custom_modelviewset import CustomModelViewSet
from apps.system.models import SystemLog, Upload, Option
from utils.exceptions import CustomError
from .serializers import HouseSerializer, RoomSerializer
from .models import House, Room
from .filters import HouseFilter, RoomFilter
from ..system.serializers import OptionDictSerializer


class HouseDictViewSet(APIView):
    permission_classes = [permissions.IsAdminUser]

    # 返回案例风格的字典参数
    def get(self, request):
        ret = {
            'style': OptionDictSerializer(Option.objects.filter(type=Option.HOUSE_STYLE, enable=True),
                                          many=True).data
        }
        return response_ok(ret)


class HouseViewSet(CustomModelViewSet):
    '''后台house CRUD操作'''
    permission_classes = [permissions.IsAdminUser]
    queryset = House.objects.filter(delete=False)
    serializer_class = HouseSerializer

    def filter_queryset(self, queryset):
        f = HouseFilter(self.request.GET, queryset=self.queryset)
        return f.qs

    def create(self, request, *args, **kwargs):
        try:
            upload_id = request.data['thumbnail']
            upload = Upload.get_instance_by_id(upload_id)
            with transaction.atomic():
                serializer = self.get_serializer(data=request.data)
                if serializer.is_valid(raise_exception=True):
                    instance = serializer.save()
                    instance.thumbnail = upload
                    instance.collect_count = random.randint(1, 100)
                    instance.save()
                    return response_ok(instance.id)
        except Exception as e:
            return response_error(str(e))

    def destroy(self, request, *args, **kwargs):
        try:
            with transaction.atomic():
                instance = self.get_object()
                instance.delete = True
                instance.save()
                SystemLog.objects.add_log(self.request.user, SystemLog.DELETE, '删除House(id=%s)信息' % instance.id)
        except Exception as e:
            return response_error(str(e))
        return response_ok()

    @action(methods=['post'], detail=True)
    def upload_thumbnail(self, request, pk):
        '''上传缩略图'''
        try:
            file = request.FILES.get('file')
            # <MultiValueDict: {'file': [<InMemoryUploadedFile: 5c193d9a33fa3363b3161b333009ed2.png (image/png)>]}>
            if not file:
                raise CustomError(u'未找到上传的数据')
            house = House.get_instance_by_id(pk)
            with transaction.atomic():
                instance = Upload.objects.upload(file, 'house')
                house.thumbnail = instance
                house.save()
        except CustomError as e:
            return response_error(e.get_error_msg())
        except Exception as e:
            return response_error(str(e))
        return response_ok()

    @action(methods=['post'], detail=True)
    def add_room(self, request, pk):
        try:
            house = House.get_instance_by_id(pk)
            name = request.data.get('name')
            describe = request.data.get('describe')
            thumbnail = request.data.get('thumbnail')
            upload = Upload.get_instance_by_id(thumbnail)
            with transaction.atomic():
                room = Room.objects.create(name=name, thumbnail=upload, describe=describe, house=house)
            return response_ok(room.id)
        except Exception as e:
            import traceback
            traceback.print_exc()
            return response_error(str(e))

    @action(methods=['post'], detail=True)
    def batch_upload_room_images(self, request, pk):
        # 房间图片批量上传
        house = House.get_instance_by_id(pk)
        file = request.FILES.get('file')
        if not file:
            return response_error(u'未找到上传的数据')
        try:
            with transaction.atomic():
                upload = Upload.objects.upload(file, 'room/')
                room = Room.objects.create(name=house.describe, thumbnail=upload, describe=house.describe, house=house)
                return response_ok()
        except Exception as e:
            return response_error(str(e))

    @action(methods=['post'], detail=False)
    def del_room(self, request):
        try:
            roomId = request.data.get('roomId')
            room = Room.get_instance_by_id(roomId)
            with transaction.atomic():
                room.delete = True
                room.save()
            return response_ok(room.id)
        except Exception as e:
            return response_error(str(e))


class RoomViewSet(CustomModelViewSet):
    '''后台room CRUD操作'''
    permission_classes = [permissions.IsAdminUser]
    queryset = Room.objects.filter(delete=False)
    serializer_class = RoomSerializer

    def filter_queryset(self, queryset):
        f = RoomFilter(self.request.GET, queryset=self.queryset)
        return f.qs

    def destroy(self, request, *args, **kwargs):
        try:
            with transaction.atomic():
                instance = self.get_object()
                instance.delete = True
                instance.save()
                SystemLog.objects.add_log(self.request.user, SystemLog.DELETE, '删除Room(id=%s)信息' % instance.id)
        except Exception as e:
            return response_error(str(e))
        return response_ok()
